package mongo

import (
	"context"
	"stock_app/models"

	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func AmountLog(p *models.ParamAmountList) (amountArr []*models.RespAmountList, err error) {
	amountArr = make([]*models.RespAmountList, 0)
	// 过滤条件
	filter := &models.AmountFilter{Time: p.Time}
	// 按照具体时间进行排序
	amountSort := bson.D{{Key: p.By, Value: p.Sort}}
	amountCollection := mongodb.Database("stock").Collection("amount")
	var cursor *mongo.Cursor
	skip := (p.Page - 1) * p.Size
	if cursor, err = amountCollection.Find(context.TODO(), filter, &options.FindOptions{Sort: amountSort, Skip: &skip, Limit: &p.Size}); err != nil {
		return
	}
	// 延迟释放游标
	defer cursor.Close(context.TODO())

	for cursor.Next(context.TODO()) {
		amount := &models.RespAmountList{}
		// 反序列化BSON
		if err = cursor.Decode(amount); err != nil {
			continue // 有日志不合法
		}
		amountArr = append(amountArr, amount)
	}
	return

}
